package com.zzyl.nursing.service.impl;

import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.ZoneOffset;
import java.util.*;

import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.baomidou.mybatisplus.core.conditions.Wrapper;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zzyl.common.constant.CacheConstants;
import com.zzyl.common.constant.HttpStatus;
import com.zzyl.common.core.page.TableDataInfo;
import com.zzyl.common.utils.DateUtils;
import com.zzyl.nursing.domain.Device;
import com.zzyl.nursing.dto.DeviceDataPageReqDto;
import com.zzyl.nursing.mapper.DeviceMapper;
import com.zzyl.nursing.task.vo.IotMsgNotifyData;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import com.zzyl.nursing.mapper.DeviceDataMapper;
import com.zzyl.nursing.domain.DeviceData;
import com.zzyl.nursing.service.IDeviceDataService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import javax.annotation.Resource;

/**
 * 设备数据Service业务层处理
 *
 * @author alexis
 * @date 2025-06-02
 */
@Slf4j
@Service
public class DeviceDataServiceImpl extends ServiceImpl<DeviceDataMapper, DeviceData> implements IDeviceDataService {
    @Autowired
    private DeviceDataMapper deviceDataMapper;
    @Autowired
    private DeviceMapper deviceMapper;

    @Resource
    private RedisTemplate<String,String> redisTemplate;

    /**
     * 查询设备数据
     *
     * @param id 设备数据主键
     * @return 设备数据
     */
    @Override
    public DeviceData selectDeviceDataById(Long id) {
        return deviceDataMapper.selectById(id);
    }

    /**
     * 查询设备数据列表
     *
     * @param deviceData 设备数据
     * @return 设备数据
     */
    @Override
    public TableDataInfo selectDeviceDataList(DeviceDataPageReqDto deviceData) {
        LambdaQueryWrapper<DeviceData> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(deviceData.getDeviceName() != null, DeviceData::getDeviceName, deviceData.getDeviceName())
                .eq(deviceData.getFunctionId() != null, DeviceData::getFunctionId, deviceData.getFunctionId());
        if (ObjectUtil.isNotEmpty(deviceData.getStartTime()) && ObjectUtil.isNotEmpty(deviceData.getEndTime())) {
            wrapper.between(DeviceData::getAlarmTime, deviceData.getStartTime(), deviceData.getEndTime());
        }

        Page<DeviceData> page = Page.of(deviceData.getPageNum(), deviceData.getPageSize());
        page = page(page, wrapper);

        TableDataInfo tableDataInfo = new TableDataInfo(page.getRecords(), page.getTotal());
        tableDataInfo.setMsg("查询成功");
        tableDataInfo.setCode(HttpStatus.SUCCESS);

        return tableDataInfo;
    }

    /**
     * 新增设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int insertDeviceData(DeviceData deviceData) {
        return deviceDataMapper.insert(deviceData);
    }

    /**
     * 修改设备数据
     *
     * @param deviceData 设备数据
     * @return 结果
     */
    @Override
    public int updateDeviceData(DeviceData deviceData) {
        return deviceDataMapper.updateById(deviceData);
    }

    /**
     * 批量删除设备数据
     *
     * @param ids 需要删除的设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataByIds(Long[] ids) {
        return deviceDataMapper.deleteBatchIds(Arrays.asList(ids));
    }

    /**
     * 删除设备数据信息
     *
     * @param id 设备数据主键
     * @return 结果
     */
    @Override
    public int deleteDeviceDataById(Long id) {
        return deviceDataMapper.deleteById(id);
    }

    /**
     * 上报数据
     *
     * @param iotMsgNotifyData
     */
    @Override
    public void batchInsertDeviceData(IotMsgNotifyData iotMsgNotifyData) {
        //判断设备是否存在
        String iotId = iotMsgNotifyData.getHeader().getDeviceId();
        LambdaQueryWrapper<Device> wrapper = new LambdaQueryWrapper<>();
        wrapper.eq(Device::getIotId, iotId);
        Device device = deviceMapper.selectOne(wrapper);
        if (device == null) {
            log.error("设备不存在，iotId:{}", iotId);
            return;
        }

        //获取到设备上报的数据，一个设备可以有多个service
        iotMsgNotifyData.getBody().getServices().forEach(data -> {
            //properties所有数据装入到map中
            Map<String, Object> map = data.getProperties();

            //处理上报时间日期
            LocalDateTime eventTime = LocalDateTimeUtil.parse(data.getEventTime(), "yyyyMMdd'T'HHmmss'Z'");
            LocalDateTime time = eventTime.atZone(ZoneId.from(ZoneOffset.UTC))
                    .withZoneSameInstant(ZoneId.of("Asia/Shanghai"))
                    .toLocalDateTime();

            //遍历map集合，批量新增数据
            List<DeviceData> list = new ArrayList<>();
            map.forEach((key, value) -> {
                DeviceData deviceData = DeviceData.builder()
                        .deviceName(device.getDeviceName())
                        .iotId(iotId)
                        .productKey(device.getProductKey())
                        .productName(device.getProductName())
                        .functionId(key)
                        .accessLocation(device.getRemark())
                        .locationType(device.getLocationType())
                        .physicalLocationType(device.getPhysicalLocationType())
                        .deviceDescription(device.getDeviceDescription())
                        .dataValue(value + "")
                        .alarmTime(time)
                        .build();
                list.add(deviceData);
            });
            log.info("开始批量保存数据:{}", list);
            //批量保存
            saveBatch(list);
            redisTemplate.opsForHash().put(CacheConstants.IOT_DEVICE_LAST_DATA,iotId, JSONUtil.toJsonStr(list));
        });

    }
}
